<?php

namespace App\Jobs;

use Illuminate\Support\Facades\Artisan;
use Symfony\Component\Console\Input\ArgvInput;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use common\utils\RedisKeys;

class Command extends Job
{
    public $args;

    public $maxProcess;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(array $args, int $maxProcess)
    {
        $this->args = $args;
        $this->maxProcess = $maxProcess;
    }

    /**
     * Job Name
     */
    public function displayName()
    {
        return implode(' ', array_slice($this->args, 1));
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if ($this->maxProcess < 1) {
            Artisan::handle(new ArgvInput($this->args));
        } else {
            $key = RedisKeys::LOCK_KEY . implode(':', $this->args);
            Redis::funnel($key)
                ->limit($this->maxProcess)
                ->releaseAfter($this->timeout)
                ->then(function () {
                    Artisan::handle(new ArgvInput($this->args));
                }, function () {
                // 超出限制直接抛弃
                    return $this->delete();
                });
        }
    }

    /**
     * The job failed to process.
     *
     * @param  Exception  $exception
     * @return void
     */
    public function failed(\Exception $exception)
    {

    }
}
